<template>
  <div style="margin-top: 20px">
    <ko-card :title="title">
      <el-form :disabled="readonly">
        <table style="width: 98%" class="tab-table">
          <tr>
            <th scope="col" width="48%" align="left">
              <label>{{ $t("business.workload.key") }}</label>
            </th>
            <th scope="col" width="48%" align="left">
              <label>{{ $t("business.workload.value") }}</label>
            </th>
            <th align="left" />
          </tr>
          <tr v-for="(row, index) in rows" v-bind:key="index">
            <td>
              <ko-data-item
                v-model="row.key"
                placeholder="e.g. foo"
                itemType="input"
                @change="syncToValue"
              />
            </td>
            <td>
              <ko-data-item
                v-model="row.value"
                placeholder="e.g. bar"
                itemType="textarea"
                @change="syncToValue"
              />
            </td>
            <td>
              <el-button
                type="text"
                style="font-size: 10px"
                @click="onHandleDelete(index)"
              >
                {{ $t("commons.button.delete") }}
              </el-button>
            </td>
          </tr>
          <tr>
            <td align="left">
              <el-button @click="onHandleAdd">{{
                $t("commons.button.add")
              }}</el-button>
            </td>
          </tr>
        </table>
      </el-form>
    </ko-card>
  </div>
</template>

<script setup lang="ts">
import KoDataItem from "@/views/domain/kubeHud/views/components/ko-data-item/index.vue";
import KoCard from "@/views/domain/kubeHud/views/components/ko-card/index.vue";
import { onMounted, ref } from "vue";

type Prop = {
  value?: Object;
  title: string;
  readonly?: boolean;
};

const props = defineProps<Prop>();
const emit = defineEmits(["update:value"]);
const rows = ref([]);

const initData = obj => {
  if (obj) {
    rows.value = [];
    for (const key in Object.keys(obj)) {
      if (Object.prototype.hasOwnProperty.call(obj, key)) {
        rows.value.push({
          index: Math.random(),
          key: key,
          value: obj[key]
        });
      }
    }
  }
};

const onHandleAdd = () => {
  const item = {
    index: Math.random(),
    key: "",
    value: ""
  };
  rows.value.push(item);
};

const onHandleDelete = index => {
  rows.value.splice(index, 1);
  syncToValue();
};

const syncToValue = () => {
  if (rows.value) {
    let obj = {};
    for (let i = 0; i < rows.value.length; i++) {
      if (rows.value[i].key !== "") {
        obj[rows.value[i].key] = rows.value[i].value;
      }
    }

    emit("update:value", obj);
  }
};

onMounted(() => {
  initData(props.value);
});
</script>
